﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPM.Entity;
using BPM.Common;

namespace BPM.Service
{
	public class BarcodeService : ServiceBase<Barcode>
	{
		public Result New(BarcodeCategory category, out Barcode entity, string barcodeNumber = null)
		{
			barcodeNumber = barcodeNumber ?? RandomBarcodeNumber();

			entity = this.Query().FirstOrDefault(b => b.Number == barcodeNumber);
			if (entity != null) return "已经存在这个条码了，添加失败。";

			entity = new Barcode()
			{
				BarcodeCategoryId = category.Id,
				Number = barcodeNumber
			};

			var context = this.NewContext();

			context.Set<Barcode>().Add(entity);
			return context.Save();
		}

		public string RandomBarcodeNumber()
		{
			return new Random().Next().ToString("D13");
		}
	}
}
